from django.db import models
from tag.models import tag
from django.db.models import F


# Create your models here.

class articles(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    category = models.ForeignKey('category.category', null=True, on_delete=models.SET_NULL)
    tags = models.ManyToManyField('tag.tag', through='article_tag')
    summary = models.CharField(max_length=255, null=True)
    artName = models.CharField(max_length=255)
    content = models.TextField()
    content_html = models.TextField()
    scan = models.SmallIntegerField(default=0)
    comment_num = models.SmallIntegerField(default=0)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    user = models.ForeignKey("user.user", on_delete=models.CASCADE)
    weight = models.SmallIntegerField(null=True)

    class Meta:
        get_latest_by = "-create_time"
        db_table = 'mblog_article'

    @property
    def all_tags(self):
        tag_obj = article_tag.objects.filter(article=self)
        tag_obj = tag_obj.annotate(id=F('tag_id'), tagName=F('tag__tag_name')).values('tag_id', 'tag__tag_name')
        return tag_obj


class article_tag(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    article = models.ForeignKey('articles', on_delete=models.CASCADE)
    tag = models.ForeignKey('tag.tag', on_delete=models.CASCADE)

    class Meta:
        db_table = "mblog_article_tag"
        unique_together = (('article', 'tag'),)
        get_latest_by = 'id'
